//
//  BuyersEditViewController.m
//  FreightAssistant
//
//  Created by leo on 15/11/5.
//  Copyright © 2015年 leo. All rights reserved.
//

#import "CustomerEditViewController.h"

#import "KKEditTableViewCell.h"

@interface CustomerEditViewController () {
    
    NSArray *_settings;
    
    NSMutableDictionary *_settingValueDictionary;
    
    KKTableFooterView *_tableFooterView;
}

@end

@implementation CustomerEditViewController

- (void)loadView {
    [super loadView];
    
    [self.tableView registerNib: [UINib nibWithNibName: NSStringFromClass([KKEditTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier: KKEditTableViewCellIdentifier];
    {
        _tableFooterView = [KKTableFooterView footerViewOfSubmitButtonWithTableView: self.tableView];
        __weak typeof(_tableFooterView) weakTableFooterView = _tableFooterView;
        self.keyboardStateBlock = ^(BOOL show){
            
            weakTableFooterView.kk_submitButton.enabled = !show;
        };
        
        [_tableFooterView.kk_submitButton addTarget: self action: @selector(actionOfSave:) forControlEvents: UIControlEventTouchUpInside];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = _kk_customerItem ? @"编辑客户" : @"新增客户";
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"KKCustomerEdit" ofType:@"plist"];
    _settings = [[NSArray alloc] initWithContentsOfFile:plistPath];
    _settingValueDictionary = [NSMutableDictionary dictionary];
    
    if (_kk_customerItem) {
        
        for (NSDictionary *itemDictionary in _settings) {
            
            NSString *key = itemDictionary[@"key"];
            NSString *value = [_kk_customerItem kk_valueForKey: key];
            
            if (key != nil && value != nil) {
                [_settingValueDictionary setValue: value forKey: key];
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods

- (void)updateCellValue:(NSString*)value fromkey:(NSString*)key {

    [_settingValueDictionary setValue: value forKey: key];
}

#pragma mark - Action methods

- (void)actionOfSave:(UIButton*)item {
    
    NSMutableDictionary *records = [NSMutableDictionary dictionary];
    
    for (NSDictionary *itemDictionary in _settings) {
        
        NSString *key = itemDictionary[@"key"];
        NSString *value = _settingValueDictionary[key];
        NSString *error = itemDictionary[@"error"];
        
        if (value == nil && error != nil) {
            [[KKResultAlertView sharedInstance] alertViewShowMessage: error andWithSuccessful: false andWithCallBack: nil];
            return;
        }
        else {
            [records setValue: value forKey: key];
        }
    }
    __weak typeof(self) weakSelf = self;
    if (_kk_customerItem) {
        
        [KKDataBaseAPIInterface editCustomerWithRecords: records withCommodityIdentifier: _kk_customerItem.kk_identifier successful:^(id object) {
            [[KKResultAlertView sharedInstance] alertViewShowMessage: @"修改成功" andWithSuccessful: true andWithCallBack:^{
                [weakSelf.navigationController popViewControllerAnimated: true];
            }];
        } faile: nil];
        
    }
    else {
        
        [KKDataBaseAPIInterface addCustomerWithRecords: records successful:^(id object) {
            [[KKResultAlertView sharedInstance] alertViewShowMessage: @"新增成功" andWithSuccessful: true andWithCallBack:^{
                [weakSelf.navigationController popViewControllerAnimated: true];
            }];
        } faile: nil];
        
    }
}

#pragma mark - UITableView methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _settings.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    KKEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: KKEditTableViewCellIdentifier forIndexPath: indexPath];
    
    NSDictionary *cellSettingInfo = _settings[indexPath.row];
    
    [cell setSettingInfo: cellSettingInfo andWithValueInfo: _settingValueDictionary];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = indexPath.row == 1 ? UITableViewCellAccessoryDetailDisclosureButton : UITableViewCellAccessoryNone;
    
    __weak typeof(self) weakSelf = self;
    cell.editHandle = ^(NSString *value, NSString *key){
        [weakSelf updateCellValue: value fromkey: key];
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    
    __weak typeof(self) weakSelf = self;
    [[KKAddressBookManager defaultManager] showInController: weakSelf completion: ^(NSDictionary *userInfo){
        
        NSLog(@"...%@", userInfo);
        NSString *phoneValue = userInfo[@"phone"];
        [_settingValueDictionary setValue: phoneValue forKey: @"phone"];
        
        [weakSelf.tableView reloadRowsAtIndexPaths: @[[NSIndexPath indexPathForRow: 1 inSection: 0]] withRowAnimation: UITableViewRowAnimationFade];
    }];
    
}

@end
